import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Tag, Space, Modal, Form, Input, Select, message, Row, Col, Avatar } from 'antd'
import { PlusOutlined, EditOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons'

interface GovernanceItem {
  id: string
  title: string
  type: 'complaint' | 'suggestion' | 'application' | 'report'
  submitter: string
  submitDate: string
  status: 'pending' | 'processing' | 'completed' | 'rejected'
  village: string
  description: string
  response?: string
  responseDate?: string
  priority: 'low' | 'medium' | 'high'
  assignedTo?: string
  deadline?: string
}

const DigitalGovernanceManagement: React.FC = () => {
  const [items, setItems] = useState<GovernanceItem[]>([])
  const [loading, setLoading] = useState(true)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingItem, setEditingItem] = useState<GovernanceItem | null>(null)
  const [searchText, setSearchText] = useState('')
  const [isResponseModalVisible, setIsResponseModalVisible] = useState(false)
  const [selectedItem, setSelectedItem] = useState<GovernanceItem | null>(null)

  // mock数据 - 与用户端DigitalGovernance页面关联
  useEffect(() => {
    const mockData: GovernanceItem[] = [
      {
        id: '1',
        title: '道路维修申请',
        type: 'application',
        submitter: '张大山',
        submitDate: '2024-01-10',
        status: 'completed',
        village: '幸福村',
        description: '村内主干道路面破损严重，申请维修',
        response: '已安排维修队伍，预计本周内完成修复',
        responseDate: '2024-01-12',
        priority: 'high',
        assignedTo: '李工',
        deadline: '2024-01-15'
      },
      {
        id: '2',
        title: '环境卫生建议',
        type: 'suggestion',
        submitter: '李小花',
        submitDate: '2024-01-08',
        status: 'processing',
        village: '和平村',
        description: '建议增加垃圾分类收集点，改善环境卫生',
        priority: 'medium',
        assignedTo: '王主任',
        deadline: '2024-01-20'
      },
      {
        id: '3',
        title: '路灯故障投诉',
        type: 'complaint',
        submitter: '王老五',
        submitDate: '2024-01-05',
        status: 'pending',
        village: '富裕村',
        description: '村口路灯连续多日不亮，影响夜间出行安全',
        priority: 'high'
      },
      {
        id: '4',
        title: '文化活动场地申请',
        type: 'application',
        submitter: '赵六',
        submitDate: '2024-01-12',
        status: 'processing',
        village: '幸福村',
        description: '申请使用村文化广场举办春节联欢晚会',
        priority: 'medium',
        assignedTo: '文化站',
        deadline: '2024-01-25'
      },
      {
        id: '5',
        title: '供水系统故障报告',
        type: 'report',
        submitter: '钱七',
        submitDate: '2024-01-15',
        status: 'completed',
        village: '和平村',
        description: '村内供水系统出现故障，影响村民正常用水',
        response: '已修复供水系统，恢复正常供水',
        responseDate: '2024-01-16',
        priority: 'high',
        assignedTo: '维修队',
        deadline: '2024-01-17'
      },
      {
        id: '6',
        title: '乡村绿化美化建议',
        type: 'suggestion',
        submitter: '孙八',
        submitDate: '2024-01-18',
        status: 'processing',
        village: '富裕村',
        description: '建议在村内主要道路两侧种植观赏树木，美化环境',
        priority: 'low',
        assignedTo: '绿化办',
        deadline: '2024-02-28'
      },
      {
        id: '7',
        title: '噪音扰民投诉',
        type: 'complaint',
        submitter: '周九',
        submitDate: '2024-01-20',
        status: 'pending',
        village: '幸福村',
        description: '村内施工工地夜间施工噪音过大，影响休息',
        priority: 'medium'
      },
      {
        id: '8',
        title: '公共设施维护申请',
        type: 'application',
        submitter: '吴十',
        submitDate: '2024-01-22',
        status: 'completed',
        village: '和平村',
        description: '申请对村内公共健身器材进行维护保养',
        response: '已完成健身器材维护，可以正常使用',
        responseDate: '2024-01-25',
        priority: 'medium',
        assignedTo: '设施维护组',
        deadline: '2024-01-30'
      },
      {
        id: '9',
        title: '交通安全隐患报告',
        type: 'report',
        submitter: '郑十一',
        submitDate: '2024-01-25',
        status: 'processing',
        village: '富裕村',
        description: '村口十字路口缺乏交通标志，存在安全隐患',
        priority: 'high',
        assignedTo: '交通管理部门',
        deadline: '2024-02-15'
      },
      {
        id: '10',
        title: '文化活动经费申请',
        type: 'application',
        submitter: '王十二',
        submitDate: '2024-01-28',
        status: 'pending',
        village: '幸福村',
        description: '申请文化活动经费用于举办村民文艺汇演',
        priority: 'medium'
      }
    ]

    setTimeout(() => {
      setItems(mockData)
      setLoading(false)
    }, 1000)
  }, [])

  const columns = [
    {
      title: '事项标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text: string, record: GovernanceItem) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.village}</div>
        </div>
      )
    },
    {
      title: '事项类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeMap = {
          complaint: { text: '投诉', color: 'red' },
          suggestion: { text: '建议', color: 'blue' },
          application: { text: '申请', color: 'green' },
          report: { text: '报告', color: 'orange' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '提交人',
      dataIndex: 'submitter',
      key: 'submitter',
      width: 100,
      render: (submitter: string) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Avatar size="small" style={{ backgroundColor: '#1890ff' }}>
            {submitter.charAt(0)}
          </Avatar>
          {submitter}
        </div>
      )
    },
    {
      title: '提交日期',
      dataIndex: 'submitDate',
      key: 'submitDate',
      width: 120
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 100,
      render: (priority: string) => {
        const priorityMap = {
          low: { text: '低', color: 'green' },
          medium: { text: '中', color: 'orange' },
          high: { text: '高', color: 'red' }
        }
        const config = priorityMap[priority as keyof typeof priorityMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '处理状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          pending: { text: '待处理', color: 'orange' },
          processing: { text: '处理中', color: 'blue' },
          completed: { text: '已完成', color: 'green' },
          rejected: { text: '已拒绝', color: 'red' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '负责人',
      dataIndex: 'assignedTo',
      key: 'assignedTo',
      width: 100,
      render: (assignedTo: string) => assignedTo || '未分配'
    },
    {
      title: '截止日期',
      dataIndex: 'deadline',
      key: 'deadline',
      width: 120,
      render: (deadline: string) => deadline || '未设置'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: GovernanceItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />}>详情</Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            size="small"
            onClick={() => handleResponse(record)}
          >
            回复
          </Button>
          {record.status === 'pending' && (
            <Button type="link" size="small">分配处理</Button>
          )}
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingItem(null)
    setIsModalVisible(true)
  }

  const handleEdit = (record: GovernanceItem) => {
    setEditingItem(record)
    setIsModalVisible(true)
  }

  const handleResponse = (record: GovernanceItem) => {
    setSelectedItem(record)
    setIsResponseModalVisible(true)
  }

  const handleSubmit = (values: any) => {
    if (editingItem) {
      // 编辑现有事项
      setItems(items.map(item => 
        item.id === editingItem.id 
          ? { ...item, ...values }
          : item
      ))
      message.success('事项信息更新成功')
    } else {
      // 添加新事项
      const newItem: GovernanceItem = {
        id: Date.now().toString(),
        title: values.title,
        type: values.type,
        submitter: '管理员',
        submitDate: new Date().toISOString().split('T')[0],
        status: 'pending',
        village: values.village,
        description: values.description,
        priority: values.priority
      }
      setItems([newItem, ...items])
      message.success('事项添加成功')
    }
    setIsModalVisible(false)
  }

  const handleResponseSubmit = (values: any) => {
    if (selectedItem) {
      setItems(items.map(item => 
        item.id === selectedItem.id 
          ? { 
              ...item, 
              response: values.response,
              responseDate: new Date().toISOString().split('T')[0],
              status: 'completed'
            }
          : item
      ))
      message.success('回复提交成功')
      setIsResponseModalVisible(false)
    }
  }

  const filteredItems = items.filter(item =>
    item.title.toLowerCase().includes(searchText.toLowerCase()) ||
    item.village.toLowerCase().includes(searchText.toLowerCase()) ||
    item.submitter.toLowerCase().includes(searchText.toLowerCase())
  )

  const statistics = {
    total: items.length,
    pending: items.filter(item => item.status === 'pending').length,
    processing: items.filter(item => item.status === 'processing').length,
    completed: items.filter(item => item.status === 'completed').length
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title="数字治理平台管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加事项
          </Button>
        }
      >
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                  {statistics.total}
                </div>
                <div style={{ color: '#666' }}>总事项</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#faad14' }}>
                  {statistics.pending}
                </div>
                <div style={{ color: '#666' }}>待处理</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                  {statistics.processing}
                </div>
                <div style={{ color: '#666' }}>处理中</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                  {statistics.completed}
                </div>
                <div style={{ color: '#666' }}>已完成</div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={8}>
            <Input
              placeholder="搜索事项标题、村庄或提交人"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={8}>
            <Select placeholder="选择事项类型" style={{ width: '100%' }} allowClear>
              <Select.Option value="complaint">投诉</Select.Option>
              <Select.Option value="suggestion">建议</Select.Option>
              <Select.Option value="application">申请</Select.Option>
              <Select.Option value="report">报告</Select.Option>
            </Select>
          </Col>
          <Col span={8}>
            <Select placeholder="选择处理状态" style={{ width: '100%' }} allowClear>
              <Select.Option value="pending">待处理</Select.Option>
              <Select.Option value="processing">处理中</Select.Option>
              <Select.Option value="completed">已完成</Select.Option>
              <Select.Option value="rejected">已拒绝</Select.Option>
            </Select>
          </Col>
        </Row>

        <Table
          loading={loading}
          columns={columns}
          dataSource={filteredItems}
          rowKey="id"
          pagination={{
            total: filteredItems.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条事项`
          }}
        />
      </Card>

      {/* 添加/编辑弹窗 */}
      <Modal
        title={editingItem ? '编辑事项' : '添加事项'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          layout="vertical"
          initialValues={editingItem || {
            type: 'suggestion',
            village: '幸福村',
            priority: 'medium',
            status: 'pending'
          }}
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="事项标题"
                name="title"
                rules={[{ required: true, message: '请输入事项标题' }]}
              >
                <Input placeholder="请输入事项标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="事项类型"
                name="type"
                rules={[{ required: true, message: '请选择事项类型' }]}
              >
                <Select placeholder="请选择事项类型">
                  <Select.Option value="complaint">投诉</Select.Option>
                  <Select.Option value="suggestion">建议</Select.Option>
                  <Select.Option value="application">申请</Select.Option>
                  <Select.Option value="report">报告</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="所属村庄"
                name="village"
                rules={[{ required: true, message: '请选择所属村庄' }]}
              >
                <Select placeholder="请选择所属村庄">
                  <Select.Option value="幸福村">幸福村</Select.Option>
                  <Select.Option value="和平村">和平村</Select.Option>
                  <Select.Option value="富裕村">富裕村</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="优先级"
                name="priority"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="请选择优先级">
                  <Select.Option value="low">低</Select.Option>
                  <Select.Option value="medium">中</Select.Option>
                  <Select.Option value="high">高</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="事项描述"
            name="description"
            rules={[{ required: true, message: '请输入事项描述' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入事项详细描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
              {editingItem ? '更新' : '添加'}
            </Button>
            <Button onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 回复弹窗 */}
      <Modal
        title="回复事项"
        open={isResponseModalVisible}
        onCancel={() => setIsResponseModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedItem && (
          <div>
            <Card size="small" style={{ marginBottom: '16px' }}>
              <p><strong>事项标题：</strong>{selectedItem.title}</p>
              <p><strong>提交人：</strong>{selectedItem.submitter}</p>
              <p><strong>提交时间：</strong>{selectedItem.submitDate}</p>
              <p><strong>事项描述：</strong>{selectedItem.description}</p>
            </Card>
            
            <Form
              layout="vertical"
              onFinish={handleResponseSubmit}
            >
              <Form.Item
                label="回复内容"
                name="response"
                rules={[{ required: true, message: '请输入回复内容' }]}
              >
                <Input.TextArea rows={4} placeholder="请输入回复内容" />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
                  提交回复
                </Button>
                <Button onClick={() => setIsResponseModalVisible(false)}>
                  取消
                </Button>
              </Form.Item>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  )
}

export default DigitalGovernanceManagement